from PyQt5.QtWidgets import (QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem,
                             QTabWidget, QWidget, QToolBar, QAction, QLabel, QStatusBar, QFileDialog, QPushButton, QMessageBox,
                             QGroupBox, QCheckBox, QSpinBox, QFormLayout, QProgressDialog)
from PyQt5.QtCore import Qt
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from collections import Counter
import logging
from visualization import CompareWidget, create_frame_stats_plot
from frame_processor import FrameProcessor

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.logger = logging.getLogger('frame_analyzer')
        self.frame_processor = None  # 帧处理器实例
        self.frames = []  # 当前加载的帧数据
        
        self._init_ui()
        self._create_toolbar()
        self._create_statusbar()
        
        # 设置窗口属性
        self.setWindowTitle('帧分析工具')
        self.setGeometry(100, 100, 1200, 800)
        
    def _init_ui(self):
        """初始化UI"""
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主窗口布局
        self.main_layout = QVBoxLayout(central_widget)
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        
        # 创建统计分析标签页
        self.plot_tab = QWidget()
        self.plot_layout = QVBoxLayout()
        self.plot_tab.setLayout(self.plot_layout)
        
        # 创建比对标签页
        self.compare_tab = QWidget()
        self.compare_layout = QVBoxLayout()
        self.compare_tab.setLayout(self.compare_layout)
        
        # 创建比对界面
        self.compare_widget = CompareWidget()
        self.compare_widget.compare_signal.connect(self._handle_compare)
        self.compare_layout.addWidget(self.compare_widget)
        
        # 添加标签页
        self.tab_widget.addTab(self.plot_tab, "统计分析")
        self.tab_widget.addTab(self.compare_tab, "文件比对")
        
        self.main_layout.addWidget(self.tab_widget)
        
    def _create_toolbar(self):
        """创建工具栏"""
        self.toolbar = QToolBar("工具栏")
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        
        # 添加工具栏按钮
        open_action = QAction("打开文件", self)
        open_action.triggered.connect(self.open_file)
        self.toolbar.addAction(open_action)
        
        export_action = QAction("导出报表", self)
        export_action.triggered.connect(self.export_report)
        self.toolbar.addAction(export_action)
        
    def _create_statusbar(self):
        """创建状态栏"""
        self.statusbar = QStatusBar()
        self.setStatusBar(self.statusbar)
        
    def open_file(self):
        """打开文件"""
        try:
            file_path, _ = QFileDialog.getOpenFileName(
                self,
                "选择帧数据文件",
                "",
                "所有文件 (*.*)"
            )
            
            if file_path:
                # 显示进度对话框
                progress = QProgressDialog("正在加载文件...", "取消", 0, 100, self)
                progress.setWindowModality(Qt.WindowModal)
                progress.setMinimumDuration(0)
                progress.setValue(0)
                
                try:
                    # 初始化帧处理器
                    if not self.frame_processor:
                        self.frame_processor = FrameProcessor("frame_schema.xml")
                    
                    # 读取帧数据
                    progress.setValue(30)
                    self.frames = self.frame_processor.read_frame(file_path)
                    
                    # 分析帧数据
                    progress.setValue(60)
                    stats = self.frame_processor.analyze_frames(self.frames, file_path)
                    
                    # 创建统计图表
                    progress.setValue(80)
                    plot_widget = create_frame_stats_plot(stats, self.frames)
                    
                    # 清除旧的显示内容
                    for i in reversed(range(self.plot_layout.count())): 
                        self.plot_layout.itemAt(i).widget().setParent(None)
                    
                    # 显示新的统计结果
                    self.plot_layout.addWidget(plot_widget)
                    
                    # 更新状态栏
                    self.statusbar.showMessage(f"已加载文件：{file_path}")
                    
                    progress.setValue(100)
                    
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"加载文件失败：{str(e)}")
                finally:
                    progress.close()
                    
        except Exception as e:
            self.logger.error(f"打开文件时发生错误: {str(e)}")
            QMessageBox.critical(self, "错误", f"打开文件失败：{str(e)}")
            
    def export_report(self):
        """导出报表"""
        try:
            if not hasattr(self, 'frames') or not self.frames:
                QMessageBox.warning(self, "警告", "请先加载帧数据文件！")
                return
                
            file_path, _ = QFileDialog.getSaveFileName(
                self,
                "保存报表",
                "帧分析报告.xlsx",
                "Excel文件 (*.xlsx)"
            )
            
            if file_path:
                # 显示进度对话框
                progress = QProgressDialog("正在导出报表...", "取消", 0, 100, self)
                progress.setWindowModality(Qt.WindowModal)
                progress.setMinimumDuration(0)
                progress.setValue(0)
                
                try:
                    # 导出报表
                    self.frame_processor.export_report(file_path)
                    progress.setValue(100)
                    QMessageBox.information(self, "完成", "报表导出成功！")
                    
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"导出报表失败：{str(e)}")
                finally:
                    progress.close()
                    
        except Exception as e:
            self.logger.error(f"导出报表时发生错误: {str(e)}")
            QMessageBox.critical(self, "错误", f"导出报表失败：{str(e)}")
            
    def _handle_compare(self, params: dict):
        """处理比对请求"""
        try:
            # 检查是否已加载文件
            if not hasattr(self, 'frames') or not self.frames:
                QMessageBox.warning(self, "警告", "请先加载第一个文件！")
                return
                
            # 选择第二个文件进行比对
            file_path, _ = QFileDialog.getOpenFileName(
                self,
                "选择要比对的文件",
                "",
                "所有文件 (*.*)"
            )
            
            if not file_path:
                return
                
            # 显示进度对话框
            progress = QProgressDialog("正在执行比对...", "取消", 0, 100, self)
            progress.setWindowModality(Qt.WindowModal)
            progress.setMinimumDuration(0)
            progress.setValue(0)
            
            try:
                # 读取第二个文件的帧数据
                progress.setValue(20)
                frames2 = self.frame_processor.read_frame(file_path)
                
                # 获取比对参数
                mode = params.get('mode', 'frame')
                start_count = params.get('start_count')
                end_count = params.get('end_count')
                
                # 执行比对
                progress.setValue(50)
                results = self.frame_processor.compare_frames_by_range(
                    self.frames,      # 第一个文件的帧数据
                    frames2,          # 第二个文件的帧数据
                    start_count=start_count,
                    end_count=end_count,
                    compare_modes=[mode] if mode else ['frame']
                )
                
                # 显示比对结果
                progress.setValue(80)
                self.compare_widget.create_compare_plot(results)
                
                # 完成
                progress.setValue(100)
                QMessageBox.information(self, "完成", "比对完成！")
                
            except Exception as e:
                QMessageBox.critical(self, "错误", f"比对过程中发生错误：{str(e)}")
            finally:
                progress.close()
                
        except Exception as e:
            self.logger.error(f"处理比对请求时发生错误: {str(e)}")
            QMessageBox.critical(self, "错误", f"处理比对请求失败：{str(e)}") 